package com.zimi.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zimi.mapper.SysOrgExtendMapper;
import com.zimi.mapper.SysRoleUserMapper;
import com.zimi.model.SysOrgExtend;
import com.zimi.model.SysRoleUser;
import com.zimi.model.SysUser;
import com.zimi.util.CommonUtil;
import com.zimi.util.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色人员授权表 Service
 *
 * @author lnintr
 * @since 2019-06-11
 */
@Service
public class SysRoleUserService {

    @Autowired
    private SysRoleUserMapper sysRoleUserMapper;
    @Autowired
    private SysOrgExtendMapper sysOrgExtendMapper;


    @Autowired
    private CommonUtil commonUtil;

    public Map getUserTree(int roleId) {

        Map map = new HashMap();
        List<SysOrgExtend> result = null;
        List<Integer> ids = null;

        // 1)权限控制
        Map map1 = commonUtil.getOrgList();
        List<SysOrgExtend> list = sysOrgExtendMapper.getMineOrgList(map1);


        //1）根据roleId去角色成员表里查询关联的数据
        List<SysRoleUser> sysRoleUsers = sysRoleUserMapper.selectList(new QueryWrapper<SysRoleUser>().lambda().eq(SysRoleUser::getRoleId, roleId));

        Map<Integer, SysRoleUser> sysRoleUserMap = new HashMap<>();
        ids = new ArrayList<>();

        //2）把1）中关联表的数据根据userId放到Map里面，把状态为1的放到idList里面
        if (sysRoleUsers != null && sysRoleUsers.size() > 0) {
            for (SysRoleUser sru : sysRoleUsers) {
                sysRoleUserMap.put(sru.getUserId(), sru);

                if (sru.getState() == 1) {
                    ids.add(sru.getUserId());
                }
            }
        }

        // 3)取出岗位机构树的集合
        result = commonUtil.getOrgPostUser(new ArrayList());
        SysRoleUser tmpSysRoleUser = null;

        //4）取出岗位中关联的人员
        if (result != null && result.size() > 0) {
            for (SysOrgExtend soe : result) {
                if (soe.getFlag() == 5) {
                    tmpSysRoleUser = sysRoleUserMap.get(soe.getId());

                    if (tmpSysRoleUser != null) {
                        if (tmpSysRoleUser.getState() == 1) {
                            soe.setChoiceFlag(true);
                        }

                        soe.setUpdateTime(tmpSysRoleUser.getUpdateTime());
                    }
                }
            }
        }


        map.put("data", result);
        map.put("checkedArr", ids);
        return map;
    }

    @Transactional
    public void saveRoleUser(SysOrgExtend sysOrgExtend, int flag) {
        int roleId = sysOrgExtend.getRoleId();

        // 1）对要修改的对象加行锁
        SysRoleUser result = sysRoleUserMapper.selectOne(new QueryWrapper<SysRoleUser>().lambda().eq(SysRoleUser::getRoleId, roleId).eq(SysRoleUser::getUserId, sysOrgExtend.getId()).last("for update"));

        SysUser user = UserUtil.getUser();
        Date updateTime = new Date();

        // 2)所属权限创建或修改
        if (result != null) {
            // 3）判断该数据已经被改过没有
            if (result.getUpdateTime() != null) {
                if (result.getUpdateTime() != null && result.getUpdateTime().getTime() != sysOrgExtend.getUpdateTime().getTime()) {
                    throw new RuntimeException("修改数据失败，数据已经被其他用户改过。");
                }
            }

            result.setUpdateUser(user.getId());
            result.setUpdateTime(updateTime);
            result.setState(flag);
            result.updateById();
        } else {
            result = new SysRoleUser();

            result.setCreateUser(user.getId());
            result.setCreateTime(updateTime);
            result.setState(1);
            result.setRoleId(roleId);
            result.setUserId(sysOrgExtend.getId());

            result.insert();
        }
    }
}